import { Button,Input  } from 'antd';
import React, { useEffect, useState } from 'react';
import { DownOutlined,LikeOutlined,DislikeOutlined,CommentOutlined,ShareAltOutlined} from '@ant-design/icons';
import { $getImg } from '../../api/getImgapi';
import { $getCommentCount, $getComments,$newComment,$getSharePost,$CheckLike,$showLike } from '../../api/postapi';
import MyNotification from "../../components/MyNotification/MyNotification";
import Comment from '../comment/comment';
import {useNavigate} from "react-router-dom";
const { TextArea } = Input;
const Post = ({ post ,avater}) => {
    //跳转页面导航
    const navigate = useNavigate();
    //通知框状态
    const [notiMsg, setNotiMsg] = useState({ type: "", description: "" });
    //显示评论状态
    const [showComments, setShowComments] = useState(false);
    const [showComments1, setShowComments1] = useState(false);
    //获取帖子的评论
    const[comments,setComments]=useState([]);
    const[comments1,setComments1]=useState([]);
    //阅读全文按钮的状态设置
    const [read,setRead]=useState(true);
    const [read1,setRead1]=useState(true);
    //为了讲useEffect中获取的图片数据在return中获得
    const [data, setData] = useState(null);
    const [data1, setData1] = useState(null);
    //获得一条帖子评论的数量
    const [commentcount,SetCommentcount]=useState(0);
    const [commentcount1,SetCommentcount1]=useState(0);
    //获取输入框评论内容的实时更新
    const [comment1, setComment1] = useState('');
    const [comment, setComment] = useState('');
    //转换时间
    const [formattedDateTime,setFormattedDateTime]=useState('');
    const [formattedDateTime1,setFormattedDateTime1]=useState('');
    //转发贴的数据
    const [newPost,setNewpost]=useState({});
    //显示帖子点赞或是不点赞
    const [isLike,setIslike]=useState(0);
    const [isLike1,setIslike1]=useState(0);
    const essay=()=>{
        setRead(!read);
    }
    const essay1=()=>{
        setRead(!read1);
    }
    //获取评论的信息
    const fetchComments = async () => {
        try {
            const response = await $getComments({postId:post.postId.toString()});
            if(response.code===1){
                setComments(response.data); // 假设响应的数据结构是一个数组
            }
        } catch (error) {
            console.error('Error fetching comments:', error);
        }
    };
    const fetchComments1 = async (postId) => {
        try {
            const response = await $getComments({postId:postId.toString()});
            if(response.code===1){
                setComments1(response.data); // 假设响应的数据结构是一个数组
            }
        } catch (error) {
            console.error('Error fetching comments:', error);
        }
    };
//输入框的回调函数，及时更新输入框的内容
    const handleCommentChange = (event) => {
        setComment1(event.target.value);
    };
    const handleCommentChange1 = (event) => {
        setComment(event.target.value);
    };
    //点击头像函数
    const handleAvatarClick = (studentId) => {
        navigate(`/layout/othermine/${studentId}`);
    };
    const handleAvatarClick1 = (studentId) => {
        navigate(`/layout/othermine/${studentId}`);
    };

    //生成新的评论
    const handlePublish = async() => {
        const response = await $newComment({postId:post.postId.toString(),content:comment1});
        if (response.code) {
            setNotiMsg({ type: "success", description: response.message});
        } else {
            setNotiMsg({ type: "error", description: response.message })
        }
        setComment1('');
    };
    const handlePublish1 = async(postId) => {
        const response = await $newComment({postId:postId.toString(),content:comment});
        if (response.code) {
            setNotiMsg({ type: "success", description: response.message});
        } else {
            setNotiMsg({ type: "error", description: response.message })
        }
        setComment('');
    };


    //获取帖子评论的数量
    const fetchCommentsCount = async () => {
        try {
            const response = await $getCommentCount({postId:post.postId.toString()});
            if(response.code===1){
                SetCommentcount(response.data); // 假设响应的数据结构是一个数组
            }
        } catch (error) {
            console.error('Error fetching CommentsCount:', error);
        }
    };
    const fetchCommentsCount1 = async (postId) => {
        try {
            const response = await $getCommentCount({postId:postId.toString()});
            if(response.code===1){
                SetCommentcount1(response.data); // 假设响应的数据结构是一个数组
            }
        } catch (error) {
            console.error('Error fetching CommentsCount:', error);
        }
    };
    const getSharePost=async ()=>{
        const response =await $getSharePost({postId:post.sharePostId.toString()});
        setNewpost(response.data);
        //获取帖子头像
        const response1 = $getImg({studentId: response.data.studentId.toString()});
        response1.then((result) => {
            if (result.code === 1) {
                const {data} = result;
                setData1(data);
            }
        });
        fetchCommentsCount1(response.data.postId);
        // 使用Date对象解析原始日期时间字符串
        const originalDateTime = new Date(response.data.createdAt);
        // 获取所需的日期时间格式，例如 "YYYY-MM-DDTHH:MM"
        setFormattedDateTime1(originalDateTime.toISOString().slice(0, 16))
        const response2=await $showLike({type:'post',id:response.data.postId});
       setIslike(response2.data);
    }
    //获取点赞和点踩的状态
    const getLikeStatus=async ()=>{
        const response=await $showLike({type:'post',id:post.postId});
        setIslike(response.data);
    }
    useEffect( ()=>{
        if(post.isShare){
           getSharePost();
           //获取转台贴的详细信息
        }else {
            //获取帖子头像
            const response = $getImg({studentId: post.studentId.toString()});
            response.then((result) => {
                if (result.code === 1) {
                    const {data} = result;
                    setData(data);
                }
            });
            fetchCommentsCount();
            // 使用Date对象解析原始日期时间字符串
            const originalDateTime = new Date(post.createdAt);
            // 获取所需的日期时间格式，例如 "YYYY-MM-DDTHH:MM"
            setFormattedDateTime(originalDateTime.toISOString().slice(0, 16))
            getLikeStatus();
        }

    },[])
    const Comt=()=>{
        fetchComments();//获取评论信息
        setShowComments(!showComments);//显示按钮的状态是否评论已近点开
    }
    const Comt1=(postId)=>{
        fetchComments1(postId);//获取评论信息
        setShowComments1(!showComments1);//显示按钮的状态是否评论已近点开
    }
   //点赞和点踩
    const Like=async (status)=>{
        const response=await $CheckLike({postId:post.postId,statue:status});
        setIslike(status);
        console.log(response);
    }
 let  status;
    switch (post.status){
        case 0:
            status = '正在审核';
            break;
        case 1:
            status = '审核通过';
            break;
        case 2:
            status = '审核失败';
            break;
    }

    let statusStyle;
    switch (post.status){
        case 0:
            statusStyle = {marginTop:'7px',fontWeight:'bold',marginRight:'20px',color:'yellow'};
            break;
        case 1:
            statusStyle = {marginTop:'7px',fontWeight:'bold',marginRight:'20px',color:'green'};
            break;
        case 2:
            statusStyle= {marginTop:'7px',fontWeight:'bold',marginRight:'20px',color:"red"};
            break;
    }

    // let likeStyle;
    // switch (post.status){
    //     case 0:
    //         statusStyle = {marginTop:'7px',fontWeight:'bold',marginRight:'20px',color:'yellow'};
    //         break;
    //     case 1:
    //         statusStyle = {marginTop:'7px',fontWeight:'bold',marginRight:'20px',color:'green'};
    //         break;
    //     case 2:
    //         statusStyle= {marginTop:'7px',fontWeight:'bold',marginRight:'20px',color:"red"};
    //         break;
    // }
    return (
        <>
            {!post.isShare?
                <div style={{marginTop: '30px', borderBottom: '4px solid rgb(220, 239, 237)', marginLeft: '20px'}}>
                <div >
                        <div className='ActivityItem-meta'
                             style={{display: 'flex', justifyContent: 'space-between', width: '100%'}}>
                            <div>发布了该贴</div>
                            <div className='right'>{formattedDateTime}</div>
                        </div>
                    <div>

                        <div className='title' style={{marginTop:'10px'}}>
                            <h2>
                                    <span>{post.title}</span>
                            </h2>
                        </div>
                        <div style={{display:'flex'}}>
                                <div className="css-1gomreu">
                                    <img src={`data:image/jpeg;base64,${data}`} alt="获取图片失败"
                                         style={{width: '50px', height: '50px'}} onClick={() => {
                                        handleAvatarClick(post.studentId)
                                    }}/>
                                </div>
                                <div className="css-1gomreu" style={{marginTop:'15px',marginLeft:'10px'}}>
                                    <span style={{fontWeight:'bold'}}>{post.nickname}</span>
                                </div>
                        </div>
                        <div className='post-content' style={{marginTop:'10px'}}>
                            {read ? post.content.substring(0, 200) : post.content}
                            {post.content.length > 200&& (
                                <Button
                                    type="link"
                                    onClick={essay}
                                    style={{ color: 'rgb(138, 216, 210)'}}
                                >
                                    {read ? '阅读全文' : '收起全文'}
                                    <DownOutlined  />
                                </Button>

                            )}
                            <div className='ContentItem-actions' style={{display:'flex',justifyContent:'space-between'}}>
                                <div>
                                        <Button icon={<LikeOutlined/>} style={isLike===1?{border:'none',backgroundcolor:'rgb(221, 240, 238)'}:{border: 'none'}} onClick={()=>{Like(1)}}>{post.likeNum}</Button>
                                        <Button icon={<DislikeOutlined/>} style={isLike===-1?{border:'none',backgroundcolor:'rgb(221, 240, 238)'}:{border: 'none'}} onClick={()=>{Like(-1)}}>{post.dislike}</Button>
                                        <Button icon={<CommentOutlined/>} style={{border: 'none'}}
                                                onClick={Comt}>{!showComments ? commentcount + '条评论' : '收起评论'}</Button>
                                      <Button icon={<ShareAltOutlined/>} style={{border: 'none'}}></Button>
                                </div>
                                <div style={statusStyle}>{status}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div>

                </div>
                {showComments && (

                    <div>
                        <div style={{display: "flex", alignItems: "center", marginTop: "20px", marginBottom: "20px"}}>
                            <img src={`data:image/jpeg;base64,${avater}`} alt="获取图片失败"
                                 style={{width: '50px', height: '50px'}}/>

                            <textarea
                                value={comment1}
                                onChange={handleCommentChange}
                                placeholder="欢迎参加讨论"
                                style={{width: '80vw'}}
                                autoSize={{
                                    minRows: 2,
                                    maxRows: 6,
                                }}
                            />
                            <Button type="primary" onClick={handlePublish}
                                    style={{backgroundColor: 'rgb(178, 234, 230)', width: '60px', height: "40px"}}>
                                发布
                            </Button>

                        </div>
                        <h3>{commentcount + "条评论"}</h3>
                        {comments.map((comment, index) => (
                            <Comment key={index} comment={comment} avater={avater}/>
                        ))}
                    </div>
                )}
                <MyNotification notiMsg={notiMsg}/>
            </div>:



                <div style={{marginTop: '30px', borderBottom: '4px solid rgb(220, 239, 237)', marginLeft: '20px'}}>
                    <div>

                        <div className='ActivityItem-meta'
                             style={{display: 'flex', justifyContent: 'space-between', width: '100%'}}>
                            <div>转发了该贴</div>
                            <div className='right'>{formattedDateTime1}</div>
                        </div>


                        <div style={{marginTop:'10px'}}>
                                <h2>
                                        <span>{newPost.title}</span>
                                </h2>

                            <div className="AuthorInfo AnswerItem-authorInfo">
                                    <div style={{display:'flex'}}>
                                        <div className="css-1gomreu">
                                            <img src={`data:image/jpeg;base64,${data1}`} alt="获取图片失败"
                                                 style={{width: '50px', height: '50px'}} onClick={() => {
                                                handleAvatarClick1(newPost.studentId)
                                            }}/>
                                        </div>

                                        <div className="css-1gomreu" style={{marginTop:'15px',marginLeft:'10px',fontWeight:'bold'}}>
                                            {newPost.nickname}
                                        </div>
                                    </div>
                            </div>
                            <div className='post-content'>
          <span>
              <div style={{marginTop: '10px'}}>{newPost.content}</div>
          </span>
                                <div className='ContentItem-actions' style={{display:'flex'}}>

                <Button icon={<LikeOutlined/>} style={isLike1===1?{border:'none',backgroundcolor:'rgb(221, 240, 238)'}:{border: 'none'}}>{newPost.likeNum}</Button>
                <Button icon={<DislikeOutlined/>} style={isLike1===-1?{border:'none',backgroundcolor:'rgb(221, 240, 238)'}:{border: 'none'}}>{newPost.dislike}</Button>
                <Button icon={<CommentOutlined/>} style={{border: 'none'}}
                        onClick={() => {
                            Comt1(newPost.postId)
                        }}>{!showComments1 ? commentcount1 + '条评论' : '收起评论'}</Button>
              <Button icon={<ShareAltOutlined/>} style={{border: 'none'}}></Button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>

                    </div>
                    {showComments1 && (

                        <div>
                            <div style={{
                                display: "flex",
                                alignItems: "center",
                                marginTop: "20px",
                                marginBottom: "20px"
                            }}>
                                <img src={`data:image/jpeg;base64,${avater}`} alt="获取图片失败"
                                 style={{width: '50px', height: '50px'}}/>

                            <textarea
                                value={comment}
                                onChange={handleCommentChange1}
                                placeholder="欢迎参加讨论"
                                style={{width: '80vw'}}
                                autoSize={{
                                    minRows: 2,
                                    maxRows: 6,
                                }}
                            />
                            <Button type="primary" onClick={()=>{handlePublish1(newPost.postId)}}
                                    style={{backgroundColor: 'rgb(178, 234, 230)', width: '60px', height: "40px"}}>
                                发布
                            </Button>

                        </div>
                        <h3>{commentcount1 + "条评论"}</h3>
                        {comments1.map((comment, index) => (
                            <Comment key={index} comment={comment} avater={avater}/>
                        ))}
                    </div>
                )}
                <MyNotification notiMsg={notiMsg}/>
            </div>
            }



        </>
    )
};


export default Post;
